﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BrandUnion.CustomData
{
    public class BookingSlotFactory
    {
        private DataContext _Context;

        public BookingSlotFactory(DataContext context)
        {
            _Context = context;
        }

        public BookingSlotFactory()
        {
            _Context = new DataContext();
        }

        private List<BookingSlot> Convert(IQueryable<Data.BookingSlot> slots)
        {
            var tmp = from slot in slots select new BookingSlot(slot, slot.Bookings.Count());
            return tmp.ToList();
        }

        public List<BookingSlot> GetAll()
        {
            var tmp = from slot in _Context.BookingSlots where !slot.Deleted orderby slot.DateTime select slot;
            return Convert(tmp);
        }


        public BookingSlot GetById(int id)
        {
            var tmp = from slot in _Context.BookingSlots where !slot.Deleted && slot.Id == id select new BookingSlot(slot, slot.Bookings.Count());
            return tmp.SingleOrDefault();
        }

        public void Delete(BookingSlot slot)
        {
            var tmp = (from s in _Context.BookingSlots where !s.Deleted && s.Id == slot.Id select s).SingleOrDefault();
            if (tmp != null)
            {
                tmp.Deleted = true;
                _Context.SubmitChanges();
            }
        }

        public void Save(BookingSlot slot)
        {
            Data.BookingSlot tmp = null;
            if (slot.Id == 0)
            {
                tmp = new Data.BookingSlot();
                _Context.BookingSlots.InsertOnSubmit(tmp);
            }
            else
            {
                tmp = (from s in _Context.BookingSlots where !s.Deleted && s.Id == slot.Id select s).Single();
            }

            tmp.DateTime = slot.DateTime;
            tmp.NoSlots = slot.NoSlots;
            _Context.SubmitChanges();
            slot.SetBookingSlot(tmp, slot.Booked);
        }
    }

    public class BookingSlot
    {
        public BookingSlot()
        {
        }

        internal BookingSlot(Data.BookingSlot slot, int bookings)
        {
            SetBookingSlot(slot, bookings);
        }

        internal void SetBookingSlot(Data.BookingSlot slot, int bookings)
        {
            this.Id = slot.Id;
            this.DateTime = slot.DateTime;
            this.NoSlots = slot.NoSlots;
            this.Booked = bookings;
            this.CID = slot.CID;
        }

        public int Id { get; private set; }
        public DateTime DateTime { get; set; }
        public int NoSlots { get; set; }
        public int Booked { get; private set; }
        public System.Data.Linq.Binary CID { get; private set; }
    }

}
